﻿using Kaskelot.SP.Services;
using Kaskelot.Web.Services;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Kaskelot.Web.UserControls
{
	public partial class PersonDetails : System.Web.UI.UserControl
	{
		public Person Current { get; set; }

		protected void Page_Load(object sender, EventArgs e)
		{
			if (Page.IsPostBack)
				return;

			Current = WebContext.Current.Person;

			if (Current != null)
			{
				NamnLabel.Text = (Current.Fornamn + " " + Current.Efternamn);
				EpostLabel.Text = !String.IsNullOrEmpty(Current.Epost) ? Current.Epost : "Ej angivet";

				TelefonnummerLabel.Text = !String.IsNullOrEmpty(Current.TelNr) ? Current.TelNr : "Ej angivet";
				MobilnummerLabel.Text = !String.IsNullOrEmpty(Current.MobTelNr) ? Current.MobTelNr : "Ej angivet";

				GatuadressLabel.Text = Current.GatuAdress;
				PostNrLabel.Text = Current.PostNr;
				PostOrtLabel.Text = Current.PostOrt;

				FornamnTextbox.Text = Current.Fornamn;
				EfternamnTextbox.Text = Current.Efternamn;
				EpostTextbox.Text = !String.IsNullOrEmpty(Current.Epost) ? Current.Epost : String.Empty;

				TelefonnummerTextbox.Text = !String.IsNullOrEmpty(Current.TelNr) ? Current.TelNr : String.Empty;
				MobiltelefonnummerTextbox.Text = !String.IsNullOrEmpty(Current.MobTelNr) ? Current.MobTelNr : String.Empty;

				GatuadressTextbox.Text = Current.GatuAdress;
				PostNrTextbox.Text = Current.PostNr;
				PostOrtTextbox.Text = Current.PostOrt;
			}
		}

		protected void SubmitButton_Click(object sender, EventArgs e)
		{
			using (WebService svc = new WebService())
			{
				Current = WebContext.Current.Person;

				if (Current != null)
				{
					Current.Fornamn = FornamnTextbox.Text;
					Current.Efternamn = EfternamnTextbox.Text;
					Current.Epost = EpostTextbox.Text;
					Current.TelNr = TelefonnummerTextbox.Text;
					Current.MobTelNr = MobiltelefonnummerTextbox.Text;
					Current.GatuAdress = GatuadressTextbox.Text;
					Current.PostNr = PostNrTextbox.Text;
					Current.PostOrt = PostOrtTextbox.Text;

					Current.Andrad = DateTime.Now;
					Current.AndradAv = Current.Personnummer;

					svc.UpdatePerson(Current);

					//Response.Redirect(Request.Url.ToString());
					string script = "<script type='text/javascript'>kaskelot.web.person.redirect();</script>";
					Page.RegisterClientScriptBlock("RedirectScript", script);
				}
			}
		}
	}
}